<template>
  <div>
    <div style="display:flex;flex-direction:row-reverse;margin-top:10px">
      <el-button :loading="saveLoading" size="mini" type="primary" @click="submitForm">保存</el-button>
    </div>

    <div v-loading="dataLoading">
      <div v-loading="saveLoading">
        <el-form
          ref="refResultForm"
          style="margin-top:20px"
          :rules="formResultRules"
          :model="formResult"
          size="mini"
          label-width="150px"
        >
          <el-row>
            <el-col :span="8">
              <el-form-item :rules="[{required:true,message:'请选择处理结果'}]" label="处理结果:" prop="processResult">
                <el-select
                  v-model="formResult.processResult"
                  placeholder="选择处理结果"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in reviewResultOptions"
                    :key="item.dictCode"
                    :label="item.dictName"
                    :value="item.dictCode"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item :rules="[{required:formResult.processResult==='0',message:'请输入处理意见'}]" label="处理意见:" prop="processAdvice">
                <el-input v-model="formResult.processAdvice" maxlength="1000" show-word-limit type="textarea" placeholder="请输入处理意见" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-form
          v-show="formResult.processResult==='1'"
          ref="refForm"
          style="margin-top:20px"
          :rules="formRules"
          :model="formData"
          size="mini"
          label-width="150px"
        >
          <el-row>
            <el-col :span="8">
              <el-form-item label="客户:" prop="mdmClientCode">
                <input-with-dialog
                  v-model="formData.mdmCustomer"
                  :props="{label:'name',value:'code'}"
                  :config="dialogConfigCustomer"
                  @change="handleChangeCustomer"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="经销商姓名:" prop="mdmCustomerName">
                <el-input v-model="formData.mdmCustomerName" placeholder="请输入经销商姓名" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="经销商身份证号:" prop="mdmCustomerIdcardNo">
                <el-input v-model="formData.mdmCustomerIdcardNo" disabled maxlength="18" placeholder="请输入经销商身份证号" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="经销商电话:" prop="mdmCustomerPhone">
                <el-input v-model="formData.mdmCustomerPhone" maxlength="11" placeholder="请输入经销商电话" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>

            <el-col :span="8">
              <el-form-item label="门店:" prop="mdmShopCode">
                <input-with-dialog
                  v-model="formData.mdmShop"
                  :props="{label:'name',value:'code'}"
                  :config="dialogConfigStore"
                  @change="handleChangeStore"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="门店编码:" prop="mdmShopCode">
                {{ formData.mdmShopCode }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="门店类型:" prop="mdmShopType">
                <el-select
                  v-model="formData.mdmShopType"
                  disabled
                  placeholder="选择门店类型"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in shopTypeOptions"
                    :key="item.dictCode"
                    :label="item.dictName"
                    :value="item.dictCode"
                  />
                </el-select>
              </el-form-item>
            </el-col>

          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="城市级别:" prop="mdmCityLevel">
                <el-select
                  v-model="formData.mdmCityLevel"
                  disabled
                  placeholder="选择城市级别"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in cityLevelOptions"
                    :key="item.dictCode"
                    :label="item.dictName"
                    :value="item.dictCode"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="门店营业状态:" prop="businessStatus">
                <el-select
                  v-model="formData.businessStatus"
                  placeholder="选择门店营业状态"
                  disabled
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in businessStateOptions"
                    :key="item.dictCode"
                    :label="item.dictName"
                    :value="item.dictCode"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="门店地址:" prop="mdmShopAddress">
                <el-input v-model="formData.mdmShopAddress" type="textarea" placeholder="请输入门店地址" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="档案维护说明:" prop="maintainDesc">
                <el-input v-model="formData.maintainDesc" maxlength="1000" show-word-limit placeholder="请填写档案维护说明" type="textarea" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <c-section title="选址评估内容">
        <c-list :column="3">
          <c-list-item label="申请人" :value="detailData.applicantName" />
          <c-list-item label="申请人电话" :value="detailData.applicantPhone" />
          <c-list-item label="选址评估进度" dict-type-code="SHOP_LOCATION_EVAL_STATE" :value="detailData.state" />
          <c-list-item label="办事处" :value="detailData.officeName" />
          <c-list-item label="办事处性质" :value="detailData.officeNature" />
          <c-list-item label="门店建设类型" dict-type-code="CONST_TYPE" :value="detailData.marketSubdType" />
          <c-list-item label="商家类别" dict-type-code="BIZMAN_TYPE" :value="detailData.businessType" />
          <c-list-item label="是否新建客户档案" :value="detailData.isNewCustomerProfile===1?'是':'否'" />
          <c-list-item label="预报图区域" :span="3" :value="formaterData(areaList,detailData.reportPicZone)" />
          <c-list-item label="所属客户" :value="detailData.clientName" />
          <c-list-item label="经销商姓名" :value="detailData.customerName" />
          <c-list-item label="经销商身份证号" :value="detailData.customerIdcardNo" />
          <c-list-item label="经销商电话" :value="detailData.customerPhone" />
          <c-list-item label="门店类型" dict-type-code="SHOP_TYPE" :value="detailData.shopType" />
          <c-list-item label="门店面积" :value="detailData.shopArea" suffix="㎡" />
          <c-list-item label="城市级别" dict-type-code="CITY_LEVEL" :value="detailData.cityLevel" />
          <!-- <c-list-item label="卖场名称" :value="detailData.shopName" /> -->
          <c-list-item label="省份" :value="detailData.provinceName" />
          <c-list-item label="城市" :value="detailData.cityName" />
          <c-list-item label="区/县" :value="detailData.areaName" />
          <c-list-item label="乡镇/街道" :value="detailData.streetName" />
        </c-list>
      </c-section>
      <div style="min-height:200px;">
        <div class="qup-title-box"><span class="border" /><span>附件信息</span></div>
        <template>
          <table-box
            ref="refDesignFile"
            :table-config="fileDataConfig"
            :table-height="400"
            :data="formData.shopAttachmentDTOList"
            show-index
          />
        </template>
        <!-- 图片预览 -->
        <el-image-viewer
          v-if="imgDialogVisible"
          :on-close="handleCloseImg"
          :url-list="[previewImg]"
        />
      </div>

    </div>
  </div>
</template>
<script>
import ElImageViewer from 'element-ui/packages/image/src/image-viewer'
import { getShopAttachment, taskValide, getAreaList } from '@/api/common.js'
import { saveFileMaintain } from '@/api/shopAddEva/index'
import BackPageMixin from '@/mixins/backPage'
import { getDetailById } from '@/api/shopAddEva'
import { getDictByPatchType } from '@/api/dataDict'
import { filterURL } from '@/utils'
export default {
  name: 'FileMaintain',
  components: { ElImageViewer },
  mixins: [BackPageMixin],
  props: {
    // id: {
    //   type: String,
    //   default: ''
    // },
    // state: {
    //   type: String,
    //   default: ''
    // }
  },
  data() {
    return {
      saveLoading: false,
      dataLoading: false,
      areaList: [], // 区域配置列表
      shopTypeOptions: [], // 门店类型
      cityLevelOptions: [], // 城市级别
      reviewResultOptions: [], // 处理结果
      businessStateOptions: [],
      formResult: {
        processResult: '',
        processAdvice: ''
      },
      formResultRules: {},
      detailData: {},
      imgDialogVisible: false,
      previewImg: '',
      url: '/pdf-file/',
      fileDataConfig: {
        hideFuncBar: true,
        tabIndex: 0,
        // 表格字段动态配置
        setting: [
          {
            prop: 'attachmentType',
            label: '附件类型',
            minWidth: '140'
          },
          {
            prop: 'attachmentName',
            label: '附件名称',
            minWidth: '140'
          },
          {
            prop: 'createBy',
            label: '创建人',
            minWidth: '140'
          },
          {
            prop: 'createTime',
            label: '上传时间',
            minWidth: '140'
          },
          {
            label: '操作',
            button: [
              {
                name: '预览',
                clickFun: this.handlePreview,
                className: 'table-handelclick-text',
                type: 'text'
              },
              {
                name: '下载',
                clickFun: this.handleDownload,
                className: 'table-handelclick-text',
                type: 'text'
              }
            ]
          }]
      },
      formRules: {
        mdmCustomerName: [
          { required: true, message: '请填写经销商姓名', trigger: 'change' }
        ],
        mdmCustomerIdcardNo: [
          { required: false, message: '请填写经销商身份证号', trigger: 'change' }
          // { pattern: /^(([0-9]{15})|([0-9]{18})|([0-9]{17}x))$/, message: '请输入正确的身份证号' }
        ],
        mdmCustomerPhone: [
          { required: true, message: '请填写经销商电话号码', trigger: 'change' },
          { pattern: /^[0-9]+$/, message: '只能输入数字' }
        ],
        mdmClientCode: [
          { required: true, message: '请选择客户', trigger: 'change' }
        ],
        mdmShopCode: [
          { required: true, message: '请选择门店', trigger: 'change' }
        ],
        maintainDesc: [
          { required: true, message: '请填写档案维护说明', trigger: 'change' }
        ]
      },
      formData: {
        applicantName: '',
        applicantCode: '',
        bizmanType: '', // 商家类别
        mdmClientCode: '',
        mdmClientName: '',
        mdmCustomerName: '',
        mdmCustomerIdcardNo: '',
        mdmCustomerPhone: '',
        mdmShopCode: '',
        mdmShopName: '',
        mdmShopType: '',
        mdmShopAddress: '',
        businessStatus: '', // 门店营业状态
        mdmOfficeName: '', // 办事处
        mdmOfficeCode: '',
        mdmShopMarketLevel: '',
        mdmShopBizType: '', // 门店业务类型
        mdmShopArea: undefined, // 门店面积
        mdmDecorationRange: '', // 装修范围
        marketSubdType: '', // 市场建设类型
        mdmCityLevel: '',
        maintainDesc: '',
        shopAttachmentDTOList: [],
        id: '',
        state: ''
      },
      provinceOptions: [],
      cityOptions: [],
      countyOptions: [],
      streetOptions: [],
      dialogConfigStore: {
        title: '门店',
        interfacePath: `/select-service/api/v1/shop/page`,
        filtersRaw: [{ 'id': 'status', 'property': 'status', 'value': '1', 'operator': '=' }],
        setting: [{ prop: 'code', title: '编码' }, { prop: 'name', title: '名称' }]
      },
      dialogConfigCustomer: {
        title: '客户',
        apiHeader: {
          'permission-code': 'storeaddeva',
          'Permission-App': 'slm'
        },
        filtersRaw: [],
        interfacePath: `/select-service/api/v1/customer/page`,
        setting: [{ prop: 'code', title: '编码' }, { prop: 'name', title: '名称' }]
      }
    }
  },
  watch: {
    'detailData.officeCode': {
      handler(v) {
        this.dialogConfigCustomer.filtersRaw = [{ 'id': 'agencyCode', 'property': 'agencyCode', 'value': v, 'operator': '=' }]
      }
    }
  },
  async  created() {
    this.dataLoading = true
    this.id = this.$route.query.id
    this.state = this.$route.query.state

    // 获取门店类型，城市级别下拉数据
    this.getDictByPatchTypeAll()
    this.getFiles()
    this.getAreaSelect()
    await getDetailById(this.id).then(res => {
      if (res.success === 1) {
        this.detailData = res.data
        this.formData.applicantCode = this.detailData.applicantCode
        this.formData.applicantName = this.detailData.applicantName
        this.formData.mdmClientName = this.detailData.clientName || ''
        this.formData.mdmClientCode = this.detailData.clientCode || ''
        this.formData.mdmCustomerPhone = this.detailData.customerPhone || ''
        this.formData.mdmCustomerName = this.detailData.customerName || ''
        this.formData.bizmanType = this.detailData.businessType || ''// 商家类别
        this.formData.mdmCustomerIdcardNo = this.detailData.customerIdcardNo || ''
        this.formData.marketSubdType = this.detailData.marketSubdType || ''
        if (this.detailData.clientCode) {
          this.dialogConfigStore.filtersRaw = [{ 'id': 'status', 'property': 'status', 'value': '1', 'operator': '=' },
            { 'id': 'customerCode', 'property': 'customerCode', 'value': this.detailData.clientCode, 'operator': '=' }
          ]
        }
        this.dataLoading = false
      }
    })

    const customerData = [{ code: this.formData.mdmClientCode, name: this.formData.mdmClientName }]
    this.$set(this.formData, 'mdmCustomer', customerData)
    const shopData = [{ code: this.formData.mdmShopCode, name: this.formData.mdmShopName }]
    this.$set(this.formData, 'mdmShop', shopData)
  },
  methods: {
    getAreaSelect() {
      getAreaList().then(res => {
        if (res.success === 1) this.areaList = res.data.records
      })
    },
    // 区域格式化数据
    formaterData(arr, value) {
      if (!value || !arr) {
        return value || ''
      }
      let list = []
      if (typeof (value) === 'string') {
        list = value.split(',')
      } else {
        list = value
      }
      const temp = []
      arr.forEach((item) => {
        const flag = list.some(v => v === item.areaCode)
        if (flag) {
          temp.push(item.areaName)
        }
      })
      return temp.toString() || value
    },
    // 获取附件
    getFiles() {
      getShopAttachment(this.id).then(res => {
        this.formData.shopAttachmentDTOList = res.data
      })
    },
    // 保存
    async  submitForm() {
      const pass = await this.$refs['refResultForm'].validate()
      if (!pass) return
      if (this.formResult.processResult === '1') {
        this.$refs['refForm'].validate((valid) => {
          if (valid) {
            this.saveLoading = true
            delete this.formData.mdmCustomer
            delete this.formData.mdmShop
            this.formData.id = this.id
            this.formData.state = this.state
            this.formData.mdmDecorationRange = 'STORES'// 装修范围
            const data = { ...this.formData, ...this.formResult }
            saveFileMaintain(data).then(res => {
              if (res.success === 1) {
                this.$message({
                  message: '档案维护成功',
                  type: 'success'
                })
                this.saveLoading = false
                this.$store.dispatch('views/goBack')// 返回列表页
              }
            }).catch(() => {
              this.saveLoading = false
            })
          }
        })
      } else {
        saveFileMaintain({
          ...this.formResult,
          ...{ id: this.id, state: this.state }
        }).then(res => {
          if (res.success === 1) {
            this.$message({
              message: '操作成功',
              type: 'success'
            })
            this.saveLoading = false
            this.$store.dispatch('views/goBack')// 返回列表页
          }
        }).catch(() => {
          this.saveLoading = false
        })
      }
    },
    handleCloseImg() {
      this.imgDialogVisible = false
    },
    handleDownload(file) {
      const a = document.createElement('a')
      const url = `/pdf-file/` + file.attachmentUrl
      const fileName = file.attachmentName
      a.href = url
      a.download = fileName
      a.click()
    },
    handlePreview(file) {
      const fileExtension = file.attachmentUrl.substring(file.attachmentUrl.lastIndexOf('.') + 1).toLowerCase()
      if (fileExtension === 'pdf') {
        // pdf预览
        const url = `/pdf-file/` + file.attachmentUrl
        const routeData = this.$router.resolve({
          path: '/viewFile',
          query: {
            src: btoa(url)
          }
        })
        window.open(routeData.href, '_blank')
      } else if (fileExtension === 'jpg' || fileExtension === 'jpeg' || fileExtension === 'png') {
      // 图片预览
        this.imgDialogVisible = true
        this.previewImg = filterURL(file.attachmentUrl)
      } else if (fileExtension === 'doc' || fileExtension === 'docx' || fileExtension === 'xlsx' || fileExtension === 'excel') {
        // word,excel预览
        window.open('http://oos.quanyou.com.cn/op/view.aspx?src=' + filterURL(file.attachmentUrl))
      } else {
        this.$message.warning('该文件类型不支持预览')
      }
    },
    // 监听门店数据变化
    async  handleChangeStore(data) {
      if (data.length !== 0) {
        // 验证当前选择门店是否有测绘任务
        const isValid = await taskValide({ shopCode: data[0].code })
        if (isValid.code) {
          this.shop = [{ code: '', name: '' }]
          this.formData.mdmShopCode = ''
          this.formData.mdmShopName = ''
          this.formData.mdmShopType = ''
          this.formData.mdmShopAddress = ''
          this.formData.businessStatus = ''
          this.formData.mdmCityLevel = ''
          this.formData.mdmShopMarketLevel = ''// 市场层级
          this.formData.mdmOfficeCode = '' // 办事处编码
          this.formData.mdmOfficeName = ''// 办事处名称
          this.formData.mdmShopBizType = ''// 门店业务类型
          this.formData.mdmShopArea = ''// 门店面积
          this.$message.warning(isValid.msg)
          return
        }

        this.formData.mdmShopCode = data[0].code
        this.formData.mdmShopName = data[0].name
        this.formData.mdmShopType = data[0].shopClassify
        this.formData.mdmShopAddress = data[0].shopAddr
        this.formData.businessStatus = data[0].businessStatus
        this.formData.mdmCityLevel = data[0].cityLevel
        this.formData.mdmShopMarketLevel = data[0].marketLevelCode

        this.formData.mdmOfficeCode = data[0].agencyCode // 办事处编码
        this.formData.mdmOfficeName = data[0].agencyName// 办事处名称
        this.formData.mdmShopBizType = data[0].businessType// 门店业务类型
        this.formData.mdmShopArea = data[0].operateArea// 门店面积

        this.$refs.refForm.validateField('mdmShopCode')
      } else {
        this.formData.mdmShopCode = ''
        this.formData.mdmShopName = ''
        this.formData.mdmShopType = ''
        this.formData.mdmShopAddress = ''
        this.formData.businessStatus = ''
        this.formData.mdmCityLevel = ''

        this.formData.mdmOfficeCode = '' // 办事处编码
        this.formData.mdmOfficeName = ''// 办事处名称
        this.formData.mdmShopBizType = ''// 门店业务类型
        this.formData.mdmShopArea = ''// 门店面积
      }
    },
    async getDictByPatchTypeAll() {
      const { CITY_LEVEL, SHOP_TYPE, REVIEW_RESULT, SHOP_BIZ_STATE } =
       await getDictByPatchType(['CITY_LEVEL', 'SHOP_TYPE', 'REVIEW_RESULT', 'SHOP_BIZ_STATE'])
      this.cityLevelOptions = CITY_LEVEL
      this.shopTypeOptions = SHOP_TYPE
      this.reviewResultOptions = REVIEW_RESULT
      this.businessStateOptions = SHOP_BIZ_STATE// 门店营业状态
    },
    // 监听所属客户数据变化
    handleChangeCustomer(data) {
      if (data.length !== 0) {
        this.dialogConfigStore.filtersRaw = [{ 'id': 'status', 'property': 'status', 'value': '1', 'operator': '=' },
          { 'id': 'customerCode', 'property': 'customerCode', 'value': data[0].code, 'operator': '=' }
        ]
        this.formData.mdmShopCode = ''
        this.formData.mdmShop = [{ code: '', name: '' }]
        this.formData.mdmClientCode = data[0].code// 客户编码
        this.formData.mdmClientName = data[0].name// 客户名称
        this.formData.mdmCustomerName = data[0].contactName//  经销商名称
        this.formData.mdmCustomerIdcardNo = data[0].credentialNo || ''// 经销商身份证号
        this.formData.mdmCustomerPhone = data[0].contactPhone// 经销商电话
      } else {
        this.formData.mdmClientCode = ''
        this.formData.mdmClientName = ''
        this.formData.mdmCustomerName = ''
        this.formData.mdmCustomerIdcardNo = ''
        this.formData.mdmCustomerPhone = ''
      }
    }

  }
}
</script>
<style lang="scss" scoped>
/deep/ .el-breadcrumb__inner{
    color: $qup-color-primary;

  }
</style>
